import React, { useRef, useState } from 'react';
import {
  ModalForm,
  ProFormRadio,
  ProFormTreeSelect,
  ProFormText,
} from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import { useIntl, useAccess, useModel } from 'umi';
import { getTree } from '@/utils';
import { getRoleList, addItem, updateItem } from '@/services/role';
import { message } from 'antd';

type AddEditProps = {
  visible: boolean;
  row?: Partial<API.RuleListItem>;
  onClose?: () => void;
  onSuccess?: () => void;
};

const AddEdit: React.FC<AddEditProps> = (props) => {
  const { initialState } = useModel('@@initialState');
  const { visible, row, onClose, onSuccess } = props;
  const handleVisibleChange = (show: boolean) => {
    if (!show) {
      onClose?.();
    }
  };
  const intl = useIntl();
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();
  const getRoles = async () => {
    const { data, code } = await getRoleList({ _all: 'ty' });
    if (code === 0) {
      return getTree(data.data);
    }
    return [];
  };

  const handleSubmit = async (values: API.RuleListItem) => {
    if (!access.isAdmin) {
      message.warning(
        intl.formatMessage({ id: row ? 'public.noUpdatePermission' : 'public.noAddPermission' }),
      );
      return true;
    }
    const { code } = row ? await updateItem({ ...values, id: row.id }) : await addItem(values);
    if (code === 0) {
      message.success(intl.formatMessage({ id: 'public.successTips' }));
      if (row) {
        location.reload();
      } else {
        onSuccess?.();
      }
      return true;
    }
    return false;
  };

  const validPhone = (rule: any, value: string) => {
    const boo = /^1[3456789]\d{9}$/.test(value);
    return boo ? Promise.resolve() : Promise.reject(rule.message);
  };
  const validPassword = (rule: any, value: string) => {
    const boo = /^\w{6,20}$/.test(value);
    return boo ? Promise.resolve() : Promise.reject(rule.message);
  };
  const checkIsSamePassword = (another: string, rule: any, value: string) => {
    const _pwd = formRef?.current?.getFieldValue(another);
    if (_pwd && _pwd !== value) {
      return Promise.reject(rule.message);
    }
    return Promise.resolve();
  };
  return (
    <ModalForm
      formRef={formRef}
      title={
        intl.formatMessage({
          id: row ? 'public.edit' : 'public.add',
        }) +
        intl.formatMessage({
          id: 'public.member',
        })
      }
      width="800px"
      layout="vertical"
      grid={true}
      rowProps={{
        gutter: 24,
      }}
      // labelAlign="left"
      // labelCol={{ span: 4 }}
      // wrapperCol={{ span: 20 }}
      visible={visible}
      onVisibleChange={handleVisibleChange}
      modalProps={{ centered: true, destroyOnClose: true, maskClosable: false }}
      onFinish={handleSubmit}
      initialValues={
        row
          ? {
              ...row,
              auth_groups: row.auth_groups.map((item: any) => item.id),
              ...(row.id ? { repassword: row.password } : {}),
            }
          : {
              gender: 1,
            }
      }
    >
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="username"
        // initialValue={row ? row.path : ''}
        label={intl.formatMessage({ id: 'member.username' })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'member.rules.username' }),
          },
        ]}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="realname"
        // initialValue={row ? row.path : ''}
        label={intl.formatMessage({ id: 'member.realname' })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'member.rules.realname' }),
          },
        ]}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="phonenumber"
        // initialValue={row ? row.path : ''}
        label={intl.formatMessage({ id: 'member.phonenumber' })}
        validateFirst={true}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'member.rules.phonenumber' }),
          },
          {
            validator: validPhone,
            message: intl.formatMessage({ id: 'public.rules.regTelphone' }),
          },
        ]}
      />
      <ProFormTreeSelect
        colProps={{
          span: 12,
        }}
        name="auth_groups"
        // initialValue={row && row.pid}
        label={intl.formatMessage({ id: 'public.role' })}
        style={{ width: '100%' }}
        placeholder={intl.formatMessage({ id: 'public.placeholder.select' })}
        fieldProps={{
          // showArrow: false,
          // filterTreeNode: true,
          // showSearch: true,
          // dropdownMatchSelectWidth: false,
          // labelInValue: true,
          treeDefaultExpandAll: true,
          allowClear: true,
          // autoClearSearchValue: true,
          treeCheckable: true,
          treeCheckStrictly: true,
          multiple: true,
          maxTagCount: 2,
          treeNodeFilterProp: 'name',
          treeNodeLabelProp: 'name',
          fieldNames: {
            label: 'name',
            value: 'id',
          },
        }}
        request={getRoles}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'member.rules.role' }),
          },
        ]}
      />
      <ProFormText.Password
        colProps={{
          span: 12,
        }}
        name="password"
        // initialValue={row ? row.path : ''}
        label={intl.formatMessage({ id: 'member.password' })}
        validateFirst={true}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'member.rules.password' }),
          },
          {
            validator: validPassword,
            message: intl.formatMessage({ id: 'public.rules.regPassword' }),
          },
          {
            validator: checkIsSamePassword.bind(null, 'repassword'),
            message: intl.formatMessage({ id: 'public.rules.samePassword' }),
          },
        ]}
      />
      <ProFormText.Password
        colProps={{
          span: 12,
        }}
        name="repassword"
        // initialValue={row ? row.path : ''}
        label={intl.formatMessage({ id: 'member.repassword' })}
        validateFirst={true}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'member.rules.repassword' }),
          },
          {
            validator: validPassword,
            message: intl.formatMessage({ id: 'public.rules.regPassword' }),
          },
          {
            validator: checkIsSamePassword.bind(null, 'password'),
            message: intl.formatMessage({ id: 'public.rules.samePassword' }),
          },
        ]}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="idcard"
        label={intl.formatMessage({ id: 'member.idcard' })}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="email"
        label={intl.formatMessage({ id: 'member.email' })}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="company"
        label={intl.formatMessage({ id: 'member.company' })}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="certificate"
        label={intl.formatMessage({ id: 'member.certificate' })}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="certificate_type"
        label={intl.formatMessage({ id: 'member.certificate_type' })}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="position"
        label={intl.formatMessage({ id: 'member.position' })}
      />
      <ProFormRadio.Group
        colProps={{
          span: 12,
        }}
        label={intl.formatMessage({ id: 'member.gender' })}
        name="gender"
        // initialValue={row ? row.status : 1}
        options={[
          {
            value: 1,
            label: intl.formatMessage({ id: 'public.male' }),
          },
          {
            value: 2,
            label: intl.formatMessage({ id: 'public.female' }),
          },
        ]}
      />
      {row && row.id && (
        <ProFormRadio.Group
          colProps={{
            span: 12,
          }}
          label={intl.formatMessage({ id: 'public.status' })}
          name="status"
          // initialValue={row ? row.status : 1}
          options={[
            {
              value: 0,
              label: intl.formatMessage({ id: 'public.enabled' }),
            },
            {
              value: 1,
              label: intl.formatMessage({ id: 'public.disabled' }),
            },
          ]}
        />
      )}
    </ModalForm>
  );
};

export default AddEdit;
